搜尋取代是一種很常見的文件編輯方式,但是如果有很多文件都需要『搜尋/取代』的話,那可就不是一件很輕鬆的工作! 所以就讓我們用一個指令讓電腦幫我們完成吧!
搜尋取代是一種很常見的文件編輯方式,但是如果有很多文件都需要『搜尋/取代』的話,那可就不是一件很輕鬆的工作!
所以今天要介紹的就是利用『下指令』來達到『搜尋/取代』的目的,只不過這一步就要很小心,如果一旦下錯指令那結果就真的會很嚴重,除非你有備份機制,例如修改程式碼時你有坐版本控制!
廢話不多說,就直接進入主題吧。搜尋取代的指令如下:
# -i 表示直接修改讀取檔案的內容,若沒有加-i則只會把修改過的內容顯示在畫面上而已。
sed –i ‘s/尋找目標字串/修改後的目標字串/g’ [輸入檔案名稱]
假設我們有一份文件如下:
Day20TestData.txt (內文資料取自 Wikipedia
Doraemon has a pocket from which he produces gadgets, medicines, and tools from the future. The pocket is called yōjigen-pocket (literally "fourth-dimensional pocket"). Some of the gadgets (dōgu) are based on real Japanese household devices with fanciful twists, but most are completely science fiction (although some may be based on folklore or religious stories). Thousands of dōgu have been featured in Doraemon." The number of gadgets has been approximated at 4,500. It is this constant variety which makes Doraemon popular both among children and among adults. In the series, the availability of dōgu sometimes depends on the money Doraemon has available, and he often says some dōgu are expensive in the future. The more famous ones include the "bamboo-copter" (which is very similar to the one that appears on the older series of Beany and Cecil), a small head accessory that allows flight; the "Anywhere Door," a door that opens up to any place the user wishes; and the "Time Machine." Some of the recurring dōgu also appear in Fujiko F. Fujio's other works, including 21-emon, Kaibutsu-kun, Kiteretsu Daihyakka, Mikio to Mikio, and Pāman.
[/code]
現在我們想把所有的 Doraemon 取代變成 小叮噹,我可以用以下指令完成:
sed -i 's/Doraemon/小叮噹/g' Day20TestData.txt
執行結果如下:
首先,先用 cat 確認一下目前檔案內容為何:
第二,執行 sed 命令來修改檔案:
sed -i 's/Doraemon/小叮噹/g' Day20TestData.txt
第三,確認是否已經修改:
成功!所有的 Doraemon 都已經被取代成 小叮噹了。
sed 就這樣嗎?當然不是,他還是有許多的功能。不過光是尋找取代這一項,就真的很好用!明天在介紹 sed 其他的功能。
鐵人賽文章分享
上一篇 常用的指令介紹之grep和awk
下一篇 常用的指令介紹之sed其他功能